package com.softwaredesign.springboot.controller;

import com.softwaredesign.springboot.entity.Role;
import com.softwaredesign.springboot.mapper.RoleMapper;
import com.softwaredesign.springboot.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMapper roleMapper;

    @GetMapping("/all")
    public Map<String, Object> findAll(@RequestParam Integer pageNum,
                                       @RequestParam Integer pageSize) {
        pageNum = (pageNum -1) * pageSize;
        List<Role> data = roleMapper.findAll(pageNum, pageSize);
        Integer total = roleMapper.findAllTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("data", data);
        res.put("total", total);
        return res;
    }

    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam String roleName) {
        pageNum = (pageNum -1) * pageSize;
        roleName = "%" + roleName + "%";
        List<Role> data = roleMapper.selectPage(pageNum, pageSize, roleName);
        Integer total = roleMapper.selectTotal(roleName);
        Map<String, Object> res = new HashMap<>();
        res.put("data", data);
        res.put("total", total);
        return res;
    }

    @PostMapping("/save")
    public int save(@RequestBody Role role) {
        return roleService.save(role);
    }

}
